package cn.zyl.demo.undertow;

import cn.zyl.demo.undertow.tests.JspClassInstance;
import cn.zyl.demo.undertow.tests.JspResourceLoader;
import io.undertow.Undertow;
import io.undertow.jsp.HackInstanceManager;
import io.undertow.jsp.JspFileHandler;
import io.undertow.jsp.JspServletBuilder;
import io.undertow.server.handlers.PathHandler;
import io.undertow.servlet.api.DeploymentInfo;
import io.undertow.servlet.api.DeploymentManager;
import io.undertow.servlet.api.ServletContainer;
import io.undertow.servlet.api.ServletInfo;
import org.apache.jasper.deploy.JspPropertyGroup;
import org.apache.jasper.servlet.JspServlet;

import javax.servlet.ServletException;
import java.util.HashMap;

/**
 * UndertowJspApplication类说明:
 *
 * @author z.y.l
 * @version v1.0
 * @date 2020-09-07
 */
public class UndertowJspApplication {
    public static void main(String[] args) {
        PathHandler servletPath = new PathHandler();
        ServletContainer container = ServletContainer.Factory.newInstance();
        DeploymentInfo builder = new DeploymentInfo()
                .setClassLoader(UndertowJspApplication.class.getClassLoader())
                .setContextPath("/servletContext")
                .setClassIntrospecter(JspClassInstance.INSTANCE)
                .setDeploymentName("servletContext.war")
                .setResourceManager(new JspResourceLoader(UndertowJspApplication.class))
                .addServlet(JspServletBuilder.createServlet("Default Jsp Servlet", "*.jsp"))
                .addServlet(new ServletInfo("jsp-file", JspServlet.class)
                        .addHandlerChainWrapper(JspFileHandler.jspFileHandlerWrapper("/test.jsp"))
                        .addMapping("/jspFile"));
        JspServletBuilder.setupDeployment(builder, new HashMap<String, JspPropertyGroup>(16), new HashMap<>(16), new HackInstanceManager());
        DeploymentManager manager = container.addDeployment(builder);
        manager.deploy();
        try {
            servletPath.addPrefixPath(builder.getContextPath(), manager.start());
            Undertow server = Undertow.builder().addHttpListener(8090, "localhost")
                    .setHandler(servletPath)
                    .build();
            server.start();
        } catch (ServletException e) {
            e.printStackTrace();
        }
    }
}
